//
//  SEGPublishViewModel.m
//  Commom
//
//  Created by 梁学彰 on 2020/6/11.
//

#import "SEGPublishViewModel.h"
#import "SEGSHManager.h"
#import "SEGCommunitySocialManager.h"

@interface SEGPublishViewModel ()
@property (nonatomic, strong) SEGSHManager* sHManager;
/**
 网络请求管理对象
 */
@property (nonatomic, strong)SEGCommunitySocialManager *manager;


@property (nonatomic,strong) NSMutableDictionary *saveDict;  //数据保存与传值(求助和聊一聊)

@end

@implementation SEGPublishViewModel
#pragma mark - life cycle
- (instancetype)initWithStatus:(SEGPublishStatus)status {
    if (self = [super init]) {
        _status = status;
        [self initData];
    }
    return self;
}

#pragma mark - init
- (void)initData {
    self.photoMaxCount = 6;
    self.sectionCount = 2;
    self.savePicArray = [[NSMutableArray alloc] init];
    self.saveUrlArray = [[NSMutableArray alloc] init];
    self.rentArray = [[NSMutableArray alloc] init];
    self.hasSubmit = NO;
    self.goodsId = (ValueToString(self.goodsIdelModel.goodsId).length) ? ValueToString(self.goodsIdelModel.goodsId) : @"0";
}

#pragma mark - send request
- (RACSignal *)getUnitData {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        // 请求押金单元
        [self.sHManager requestRentUnit:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            NSDictionary* dic = [result objectForKey:@"data"];
            if ([dic count] > 0) {
                NSArray *resultArray = [dic valueForKey:@"result"];
                if (resultArray && [resultArray isKindOfClass:[NSArray class]]) {
                    [resultArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([obj isKindOfClass:[NSDictionary class]]) {
                            [self.rentArray addObject:obj];
                        }
                    }];
                }
                
            }
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
    return signal;
}

- (RACSignal *)submitHelpCardRequestWithContent:(NSString *)content name:(NSString *)name phone:(NSString *)phone {

    return [RACSignal concat:@[[self upLoadSignal],[self sendHelpCardRequestWithContent:content name:name phone:phone]]];
}

- (RACSignal *)sendHelpCardRequestWithContent:(NSString *)content name:(NSString *)name phone:(NSString *)phone {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        //把数据保存在字典中，进行传输
        SEGProfileModel *sysAccount = [SEGProfileManager sharedManager].profile;
        NSString* nickName = sysAccount.nickname;
        if ([nickName length] == 0) {
            nickName = sysAccount.tel;
        }
        
        NSString* quizPicUrl = [self.saveUrlArray componentsJoinedByString:@","];
        self.saveDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                         @"", @"objId",
                         @"2", @"objType",
                         content, @"quizContent",
                         sysAccount.userId, @"userId",
                         @"10002", @"quizTypeId",
                         @"3", @"quizRangeId",
                         sysAccount.cityId, @"regionId", //城市编码
                         sysAccount.jobCommunity, @"organId", //小区id
                         @"", @"linkUrl",
                         @"", @"linkTitle",
                         quizPicUrl, @"quizPic", //图片拼接
                         [NSString stringWithFormat:@"来自%@ %@", sysAccount.city, sysAccount.communityName], @"communityName", //城市+名称
                         nickName, @"creator",
                         kAccountCommunityID, @"communityId",
                         @"1", @"isBroadCast",
                         self.helpLabelModel.labelId, @"labelId",
                         nil];
        if (name.length > 0) {
            [self.saveDict setObject:name forKey:@"contact"];
        }
        if (phone.length > 0) {
            [self.saveDict setObject:phone forKey:@"contactTel"];
        }
        
        [self.manager requestSaveQuizWithParams:self.saveDict Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
            if (isSuccessed) {
        
                //帮帮发帖积分行为设置 (5.0.0 邻里圈帮帮发帖 要加moduleCode)
                [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.postForHelp module:SEGIntegralModule.neighborhoodCircle businessID:nil finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                }];
                //刷新帮帮
                [[NSNotificationCenter defaultCenter] postNotificationName:@"SEGHelpDeatilViewControllerNotification" object:nil];
                [subscriber sendCompleted];
        
            }else {
                self.hasSubmit = NO;
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:codeType.integerValue userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
            }

        }];
        return nil;
    }];
    return signal;
}




#pragma mark - custom delegate

#pragma mark - system delegate





/**
 * 提交集市
 * @author Wendy
 * @param dict 参数字典
 */
- (RACSignal *)submitGoodsIdelWithDict:(NSDictionary *)dict {
    return [RACSignal concat:@[[self upLoadSignal],[self requestSubmitGoodsIdelWithDict:dict]]];
}

- (RACSignal *)upLoadSignal {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        self.hasSubmit = YES;
        //只上传没有url的图片，也就是新增图片
        NSArray *uploadArr = [self.savePicArray subarrayWithRange:NSMakeRange(self.saveUrlArray.count, self.savePicArray.count - self.saveUrlArray.count)];
        if(uploadArr.count > 0) {
            [[SEGMultipartfileuploadManager sharedManager] requestMultipartfileuploadWithImage:uploadArr progress:nil completed:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if(isSuccessed) {
                    NSArray *data = result[@"data"];
                    //存储图片链接
                    [self.saveUrlArray addObjectsFromArray:data];
                    [subscriber sendCompleted];
                }else {
                    self.hasSubmit = NO;
                    [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                }
            }];
        }else {
            [subscriber sendCompleted];
        }
        return nil;
    }];
    return signal;
    
}


/**
 * 请求提交闲置接口
 * @author Wendy
 * @param dict 参数字典
 */
- (RACSignal *)requestSubmitGoodsIdelWithDict:(NSDictionary *)dict {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        NSMutableDictionary *parms = [NSMutableDictionary dictionaryWithDictionary:dict];
        [parms setValuesForKeysWithDictionary:@{
            @"goodsId" : self.goodsId?self.goodsId:@"0", // 0表示新增，大于0表示修改
            @"type" : [NSString stringWithFormat:@"%lu",(unsigned long)self.classifyId], // 发布类型
            @"classId" : self.classId, // 商品分类
            @"img" : [self.saveUrlArray componentsJoinedByString:@","] // 商品图片，多个用','分格
        }];
        if (self.status == SEGPublishStatus_Republished) {
            [parms setObject:@"1" forKey:@"status"];
        }
        
        //请求提交接口
        [self.sHManager requestSubmitGoodsIdelWithParams:parms finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            if (isSuccessed) {
                self.hasSubmit = YES;
                //闲置发帖积分行为设置
                [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.idle module:SEGIntegralModule.neighborhoodCircle businessID:nil finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) { 
                }];
                
                [subscriber sendCompleted];
            }else {
                self.hasSubmit = NO;
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:codeType.integerValue userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
            }
        }];
        return nil;
    }];
    return signal;
    
}

- (SEGSHManager*)sHManager {
    if (!_sHManager) {
        _sHManager = [[SEGSHManager alloc] init];
    }
    return _sHManager;
}

#pragma mark - setter and getter
- (void)setGoodsIdelModel:(SEGQueryGoodsIdelModel *)goodsIdelModel {
    _goodsIdelModel = goodsIdelModel;
    self.goodsId = (ValueToString(self.goodsIdelModel.goodsId).length) ? ValueToString(self.goodsIdelModel.goodsId) : @"0";
}

- (SEGCommunitySocialManager *)manager {
    if (!_manager) {
        _manager = [[SEGCommunitySocialManager alloc] init];
    }
    return _manager;
}


@end
